<?php

namespace app\enterprise\service;

use app\enterprise\model\staff\Staff as staffModel;
use app\enterprise\model\Parameter as parameterModel;
use think\exception\ValidateException;

class ImportService
{
    protected $dictMap = [];

    public function __construct()
    {
        // 加载字典项 name => id
        $dicts = parameterModel::listAll([]);
        foreach ($dicts as $item) {
            $this->dictMap[$item['para_name']] = $item['id'];
        }
    }

    /**
     * 导入人员数据
     *
     * @param string $filePath Excel 文件路径
     * @param int $companyId 所属企业ID
     * @return array
     */
    public function importStaff($filePath, int $companyId, int $creatorId)
    {
        try {
            $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($filePath);
            $worksheet = $spreadsheet->getActiveSheet();
            $rows = $worksheet->toArray();

            // 跳过标题行
            array_shift($rows);

            $successCount = 0;
            $failures = [];

            $statusArr = ['在职' => 1, '离职' => 2];
            $staffTypeArr = ['内部人员' => 1, '项目人员' => 2];

            $insertData[] = [];
            $accountArr[] = [];
            foreach ($rows as $index => $row) {
//                list($username, $sex, $idcard, $mobile, $account, $staff_type, $edu_name, $level_name, $job_name, $job_status) = $row;
                list($username, $sex, $idcard, $mobile, $staff_type) = $row;

                if (empty($username)) {
                    throw new ValidateException('第'.($index + 2).'名称为空');
                }
                if (empty($sex)) {
                    throw new ValidateException('第'.($index + 2).'性别为空');
                }
                if (empty($idcard)) {
                    throw new ValidateException('第'.($index + 2).'身份证号为空');
                }

                if (empty($mobile)) {
                    throw new ValidateException('第'.($index + 2).'手机号为空');
                }

//                if (empty($account)) {
//                    throw new ValidateException('第'.($index + 1).'账号为空');
//                }

                // 判断$accountArr是否已经存在了当前账号
//                if (in_array($account, $accountArr)) {
//                    throw new ValidateException('第'.($index + 2).'账号重复');
//                }

                // 判断账号是否有重复的
//                $exist = staffModel::where('account', $account)->where('company_id', $companyId)->find();
//                if ($exist) {
//                    throw new ValidateException('第'.($index + 2).'账号已存在');
//                }

                // 验证数据格式
                if (!preg_match('/^1[3456789]\d{9}$/', $mobile)) {
                    throw new ValidateException('第'.($index + 2).'手机号格式错误');
                }
                if (!preg_match('/^(\d{15}$|^\d{17}[\dXx])$/', $idcard)) {
                    throw new ValidateException('第'.($index + 2).'身份证号格式错误');
                }


//                $edu_id = $this->getDictId($edu_name);
//                $level_id = $this->getDictId($level_name);
//                $job_id = $this->getDictId($job_name);

//                if (!$edu_id || !$level_id || !$job_id) {
//                    $failures[] = ['row' => $index + 2, 'reason' => '学历/级别/岗位不存在'];
//                    throw new ValidateException('第'.($index + 2).'学历/级别/岗位不存在');
//                }

//                if (!isset($job_status) || !array_key_exists($staff_type, $staffTypeArr)) {
//                    throw new ValidateException('第'.($index + 2).'员工状态错误');
//                }

//                if (!isset($staff_type) || !array_key_exists($staff_type, $staffTypeArr)) {
//                    throw new ValidateException('第'.($index + 2).'员工类别错误');
//                }

                $data = [
                    'username' => $username,
                    'idcard' => $idcard,
                    'sex' => $sex,
//                    'account' => $account,
                    'staff_type' => $staffTypeArr[$staff_type],
                    'mobile' => $mobile,
//                    'edu_id' => $edu_id,
//                    'level_id' => $level_id,
//                    'job_id' => $job_id,
//                    'job_status' => $statusArr[$job_status],
                    'company_id' => $companyId,
                    'creator_id' => $creatorId,
                    'password'=>md5(substr($idcard, -6))
                ];
                $successCount = $successCount + 1;
                $insertData[] = $data;
            }
//            dump($insertData);
//            die;
            (new staffModel())->saveAll($insertData);

            return [
                'total' => count($rows),
                'success_count' => $successCount,
//                'failure_count' => count($failures),
//                'failures' => $failures,
            ];
        } catch (\Exception $e) {
            throw new ValidateException('导入失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取字典项 ID
     */
    protected function getDictId($name)
    {
        return $this->dictMap[$name] ?? null;
    }
}
